package shs

import (
	"iter"

	"github.com/liyue201/gostl/ds/skiplist"
	"github.com/liyue201/gostl/utils/comparator"
)

var _ Index = (*SkipListIndex)(nil)

type SkipListIndex skiplist.Skiplist[string, uint64]

func NewSkipListIndex() *SkipListIndex {
	return (*SkipListIndex)(skiplist.New[string, uint64](comparator.StringComparator, skiplist.WithMaxLevel(15)))
}

func (s *SkipListIndex) Get(key []byte) (uint64, error) {
	list := (*skiplist.Skiplist[string, uint64])(s)
	return list.Get(bytesToString(key))
}

func (s *SkipListIndex) Set(key []byte, value uint64) error {
	list := (*skiplist.Skiplist[string, uint64])(s)
	list.Insert(bytesToString(key), value)
	return nil
}

func (s *SkipListIndex) Delete(key []byte) error {
	list := (*skiplist.Skiplist[string, uint64])(s)
	exists := list.Remove(bytesToString(key))
	if !exists {
		return ErrKeyNotFound
	}
	return nil
}

func (s *SkipListIndex) Iterator() iter.Seq2[[]byte, uint64] {
	return func(yield func([]byte, uint64) bool) {
		list := (*skiplist.Skiplist[string, uint64])(s)
		list.Traversal(func(key string, value uint64) bool {
			if !yield(stringToBytes(key), value) {
				return false
			}
			return true
		})
	}
}
